package com.fyzk.activity.user;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.lottery.togetherbuy.HM_Popupwindow;
import com.fyzk.base.BaseActivity;
import com.fyzk.bean.ProvinceBean;
import com.fyzk.net.Commands;
import com.fyzk.utils.AssetsUtil;
import com.fyzk.utils.BankUtils;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.view.TopTitleView;
import com.tyjc.lottery.R;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;

@ContentView(R.layout.activity_bind_bank)
public class BindBankActivity extends BaseActivity implements HM_Popupwindow.HM_PopuponItemListener {

    @ViewInject(R.id.bangding_top_rl)
    private TopTitleView topView;

    private String userName;
    private String realName;

    @ViewInject(R.id.bangding_spi_yinname)
    private EditText bankName_et;

    @ViewInject(R.id.bangding_yinnum)
    private EditText et_yinNum;

    @ViewInject(R.id.bind_provinces_et)
    private EditText provinces_et;

    @ViewInject(R.id.bind_address_et)
    private EditText address_et;
    @ViewInject(R.id.tv_sure)
    private TextView tv_sure;

    private String[] bankName;
    private HM_Popupwindow bankName_popup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bankName = getResources().getStringArray(R.array.bank_name);
        userName = getIntent().getStringExtra(IntentParamUtils.USERNAME);
        realName = getIntent().getStringExtra(IntentParamUtils.REALNAME);
        initView();
        initJsonData();
    }

    private void initView() {
        topView.setOnTitleClickListener(this);
        bankName_et.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                bankName_popup.showPopupWindow(bankName_et);
            }
        });

        provinces_et.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showPickerView();
            }
        });

        bankName_popup = new HM_Popupwindow(this, AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT, bankName);
        bankName_popup.setCheckItem(-1);
        bankName_popup.setHm_PopupOnItemListener(this);

        tv_sure.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (et_yanZheng()) {
                    requestBindBankCard();
                }
            }
        });
    }

    private List<ProvinceBean> options1Items = new ArrayList<>();
    private List<List<String>> options2Items = new ArrayList<>();

    private void initJsonData() {
        String mProvinceDataStr = AssetsUtil.getJson(this, "json/province.json");
        List<ProvinceBean> provinceBean = JSON.parseArray(mProvinceDataStr, ProvinceBean.class);
        options1Items = provinceBean;
        for (int i = 0; i < provinceBean.size(); i++) {//遍历省份
            List<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            for (int c = 0; c < provinceBean.get(i).getCity().size(); c++) {//遍历该省份的所有城市
                String CityName = provinceBean.get(i).getCity().get(c).getName();
                CityList.add(CityName);//添加城市
            }
            /**
             * 添加城市数据
             */
            options2Items.add(CityList);
        }
    }

    String selectProvince;
    String selectCity;

    /**
     * 弹出选择器
     */
    private void showPickerView() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                selectProvince = options1Items.get(options1).getPickerViewText();
                selectCity = options2Items.get(options1).get(options2);
                provinces_et.setText(selectProvince + selectCity);
            }
        }).setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        pvOptions.setPicker(options1Items, options2Items);//二级选择器
        pvOptions.show();
    }

    /**
     * 请求绑定银行卡
     */
    private void requestBindBankCard() {
        JSONObject request = new JSONObject();
        try {

            String branch = address_et.getText().toString();
            request.put("branch", TextUtil.isEmpty(branch) ? "" : branch);
            request.put("province", TextUtil.isEmpty(selectProvince) ? "" : selectProvince);
            request.put("city", TextUtil.isEmpty(selectCity) ? "" : selectCity);
            request.put("bankCard", et_yinNum.getText().toString());
            request.put("bankName", bankName_et.getText().toString());
            httpPostJson(CommandUtil.BINDBANK, Commands.BINDBANKCARD, request, true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        AppToast.getToast().show("绑定银行卡成功");
        finish();
    }

    @Override
    protected void onFailure(int requestCode, String errorCode, String message) {
        if (errorCode.equals("40002")) {
            AppToast.getToast().show("用户不存在");
        } else if (errorCode.equals("40014")) {
            AppToast.getToast().show("真实姓名没填写");
        } else if (errorCode.equals("40015")) {
            AppToast.getToast().show("该卡号已绑定");
        } else {
            AppToast.getToast().show("网络异常");
        }
    }

    private boolean et_yanZheng() {
        if (isNull(bankName_et)) {
            AppToast.getToast().show("银行名称不能为空");
            return false;
        }

        if (isNull(et_yinNum)) {
            AppToast.getToast().show("银行卡号不能为空");
            return false;
        }

        if(!BankUtils.checkBankCard(et_yinNum.getText().toString().trim())){
            AppToast.getToast().show("请输入正确的银行卡号");
            return false;
        }

        if (isNull(provinces_et)) {
            AppToast.getToast().show("开户省市不能为空");
            return false;
        }

        if (isNull(address_et)) {
            AppToast.getToast().show("开户行不能为空");
            return false;
        }

        return true;
    }

    /**
     * 非空验证
     */
    private boolean isNull(EditText editText) {
        if (editText.getText() == null || editText.getText().toString().equals("")) {
            editText.requestFocus();
            return true;
        }
        return false;
    }

    @Override
    public void onItem(int position) {
        bankName_et.setFocusable(false);
        bankName_et.setText(bankName[position]);
        bankName_et.setHint("请选择银行名称");
    }

    @Override
    public void popupShow() {
    }

    @Override
    public void popupDismiss() {
    }

}
